package blog.spring.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import blog.core.exception.BaseException;
import blog.core.exception.DependException;
import blog.core.exception.NotFoundException;

public class BlogController {

	private final String CURRENT_DIR;

	public BlogController(String CURRENT_DIR) {
		this.CURRENT_DIR = CURRENT_DIR;
	}

	@ExceptionHandler
	public String exp(HttpServletRequest req,HttpServletResponse resp, Exception ex) {
		req.setAttribute("e", ex);
		if (ex instanceof BaseException) {
			resp.setStatus(((BaseException)ex).getHTTP_STATUS());
			if (ex instanceof NotFoundException)
				return "error/404";
			if (ex instanceof DependException)
				return "error/error";
		} else {
			resp.setStatus(500);
			return "error/500";
		}
		return null;
	}

	/**
	 * 重定向到指定映射路径
	 *
	 * @param path
	 *            路径
	 * @return 重定向返回值
	 */
	protected String redirect(String path) {
		return "redirect:" + path.trim();
	}

	/**
	 * 重定向到项目主页
	 *
	 * @return 主页重定向返回值
	 */
	protected String redirectIndex() {
		return "redirect:/index";
	}

	/**
	 * 重定向到当前主页
	 *
	 * @return
	 */
	protected String redirectCurentIndex() {
		return "redirect:/" + CURRENT_DIR + "/index";
	}

	/**
	 * 转发到当前主页
	 *
	 * @return
	 */
	protected String forwardCurentIndex() {
		return CURRENT_DIR + "/index";
	}

	/**
	 * 转发到当前详情页面
	 *
	 * @return
	 */
	protected String forwardCurentInfo() {
		return CURRENT_DIR + "/info";
	}

	/**
	 * 转发到当前更新页面
	 *
	 * @return
	 */
	protected String forwardCurentUpdate() {
		return CURRENT_DIR + "/update";
	}

	/**
	 * 转发到当前添加页面
	 *
	 * @return
	 */
	protected String forwardCurentAdd() {
		return CURRENT_DIR + "/add";
	}

	/**
	 * 给ModelMap带入异常信息
	 * @param map ModelMap
	 * @param e 异常对象
	 */
	protected void addException(ModelMap map, Exception e) {
		map.addAttribute("formError", e);
	}
}
